package com.wzy.leecode;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: wzy
 * @Date: 2021/10/31/9:23
 * @Description: 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 */
public class removeLastNode {
    public static void main(String[] args) {

    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        // 循环
        /*
        ListNode node = new ListNode(0, head);
        int length = 0;
        while (head != null){
            length++;
            head = head.next;
        }
        ListNode cur = node;
        for (int i = 0; i < length - n ; i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        ListNode ans = node.next;
        return ans;*/
        // 快慢指针
        ListNode node = new ListNode(0, head);
        ListNode first = head;
        ListNode second = node;
        for (int i = 0; i < n; i++) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        ListNode ans = node.next;
        return ans;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
